# -*- coding: utf-8 -*-
"""
Created on Sun Oct 17 15:37:38 2021

@author: zhuo木鸟

从模型筛选一节得出的最佳模型为 SVC，本代码将结合数据集，采用各大评价指标，综合评价模型的效果
"""

import pickle
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, precision_score, recall_score
import pandas as pd

if __name__ == '__main__':
    # 读取数据预处理过后的数据
    datasets = pickle.load(open(r'../results/datasets_2_pca.pkl', 'rb'))
    # wave_number = pickle.load(open(r'../results/wave_number_2.pkl', 'rb'))
    herbs_op = pickle.load(open(r'../results/datasets_2_herbs_op.pkl', 'rb'))
    
    # 按照7:3的比例将数据集拆分为训练集和测试集
    X_train ,X_test, y_train, y_test = train_test_split(datasets,
                                                        herbs_op,
                                                        test_size=0.3)
    # 产生待筛选的参数网格
    svc_model = SVC(C=3.0, kernel='linear')
    # 模型训练
    svc_model.fit(X_train, y_train)
    y_train_predict = svc_model.predict(X_train)
    print('SVC 模型在训练集中的精确度为：', accuracy_score(y_train, y_train_predict))
    print('SVC 模型在训练集中的准确率为：', precision_score(y_train, y_train_predict, average='weighted'))
    print('SVC 模型在训练集中的召回度为：', recall_score(y_train, y_train_predict, average='weighted'))
    
    y_test_predict = svc_model.predict(X_test)
    print('SVC 模型在测试集中的精确度为：', accuracy_score(y_test, y_test_predict))
    print('SVC 模型在测试集中的准确率为：', precision_score(y_test, y_test_predict, average='weighted'))
    print('SVC 模型在测试集中的召回度为：', recall_score(y_test, y_test_predict, average='weighted'))
    
    pickle.dump(svc_model, open(r'../results/svc_model.pkl', 'wb'))
    
    # 我录那些没有 OP 的数据
    datasets_without_op = pickle.load(open(r'../results/datasets_2_without_op_pca.pkl', 'rb'))
    datasets_without_op_index = pickle.load(open(r'../results/datasets_2_without_op.pkl', 'rb'))
    datasets_without_op_index = datasets_without_op_index.index
    
    
    herbs_op_predict = svc_model.predict(datasets_without_op)
    
    herbs_no_op_df = pd.concat([pd.Series(datasets_without_op_index), pd.Series(herbs_op_predict, name='OP')], axis=1)
    herbs_no_op_df.to_excel(r'../results/问题2药材产出地预测结果.xlsx')